
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

class Operation{
    //增加
    public void add(Connection connection, int ID, String name) throws SQLException {
        String sql = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, ID);
        statement.setString(2, name);
        int n = statement.executeUpdate();
        statement.close();//可有可无，因为出了函数就销毁了
        System.out.println("n = " + n);
    }
    //删除
    public void  delete(Connection connection, int ID) throws SQLException {
        String sql = "delete from student where ID = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, ID);
        int n = statement.executeUpdate();
        System.out.println("n = " + n);
    }
    //查找
    public void select(Connection connection) throws SQLException {
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        System.out.println(statement.executeQuery());
    }
    //修改
    public void update(Connection connection, int ID, String name) throws SQLException {
        String sql = "update student set ID = ?, name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, ID);
        statement.setString(2, name);
        int n = statement.executeUpdate();
        System.out.println("n = " + n);
    }

}
public class JDBC {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java105?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.建立连接,注意这里要抛异常
        Connection connection = dataSource.getConnection();
        //3.通过用户输入来改变数据库中的值a
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学生ID:");
        int ID = scanner.nextInt();
        System.out.println("请输入学生姓名:");
        String name = scanner.next();
        //执行构造的sql语句
        Operation operation = new Operation();
        operation.select(connection);
        //5.最后关闭释放相关资源(注意，先创建的后释放，后创建的先释放)
        connection.close();
    }
}
